<?php
/**
 * 店铺管理 
*
* @author karl <karl.tang@aiyuangong.com>
* @link http://www.aiyuangong.com
*/
namespace app\admin\controller\store;

use app\admin\Controller;
use think\Db;
use think\Exception;
use think\Validate;

class Store extends Controller
{
    use \app\admin\traits\controller\Controller;

    protected static $blacklist = [
        'clear','delete','deleteforever','resume','recyclebin'
    ];

    protected static $_spec_area = 1; // 规格-服务地区
    protected static $_spec_type = 2; // 规格-类型
    protected static $_spec_city = 100; // 规格-服务地市
    
    public function index(){
        // 店铺等级
        $gradeList = \Fields::getById('store_grade');
        //店铺类型
        $classList = \Fields::getById('store_class');
        
        $name = $this->request->param('name/s','');
        $grade_id = $this->request->param('grade_id/d',0);
        $member_name = $this->request->param('member_name/s','');
        $class_id = $this->request->param('class_id/d',0);
        $where['is_own_shop'] = 0;
        if($name){
            $where['name'] = ['like','%'.$name.'%'];
        }
        if($member_name){
            $where['member_name'] = ['like','%'.$member_name.'%'];
        }
        if($grade_id){
            $where['grade_id'] = $grade_id;
        }
        if($class_id){
            $where['sc_id'] = $class_id;
        }
        if ($this::$isdelete !== false) {
            $where['isdelete'] = $this::$isdelete;
        }
        $list = $this->datalist(model('store'), $where);//Db::name('store')->where($where)->paginate();
        $this->view->assign('grade_list',$gradeList);
        $this->view->assign('class_list',$classList);
        return $this->view->fetch();
    }
    
    /**
     * 自营店铺
     */
    public function own_shop(){
        $name = $this->request->param('name/s','');
        $member_name = $this->request->param('member_name/s','');
        $where['is_own_shop'] = 1;
        if($name){
            $where['name'] = ['like','%'.$name.'%'];
        }
        if($member_name){
            $where['member_name'] = ['like','%'.$member_name.'%'];
        }
        $list = $this->datalist(model('store'),$where);
        return $this->view->fetch();
    }
    
    /**
     * 添加店铺
     */
    public function add(){
        $store_id = $this->request->param('id/d',0);
        if($this->request->isPost()){
            $type = $this->request->param('type/s','');
            Db::startTrans();
            try {
                $data['member_name'] = $this->request->post('member_name/s','');
                $data['seller_name'] = $this->request->post('seller_name/s','');
                $data['store_name'] = $this->request->post('store_name/s','');
                $member_info = model('member')->getMember('id',array('name'=>$data['member_name']));
                if(empty($member_info)){
                    return ajax_return_adv_error('店主账号未注册，请先注册');
                }
                $memberId = $member_info['id'];
                $rule = [
                    'member_name|店主账号' => 'max:250|unique:store_joinin,member_name',
                    'seller_name|店主卖家账号' => 'length:3,15|unique:seller,seller_name',
                    'store_name|店铺名称' => 'max:50|unique:store,name',
                ];
                $msg = [
                    'member_name.unique' => '店主账号已被占用',
                    'seller_name.length' => '店主卖家账号必须是3~15位',
                    'seller_name.unique' => '店主卖家账号名称已被其它店铺占用',
                ];
                $validate = new Validate($rule,$msg);
                if(!$validate->check($data)){
                    return ajax_return_adv_error($validate->getError());
                }
                $memberId = $member_info['id'];
                //添加store
                $saveArray = [
                    'name' => $data['store_name'],
                    'member_id' => $memberId,
                    'areacode' => 0,
                    'member_name' => $data['member_name'],
                    'seller_name' => $data['seller_name'],
                    'bind_all_gc' => $type == 'own' ? 1 : 0,
                    'store_state' => 1,
                    'time' => time(),
                    'is_own_shop' => $type == 'own' ? 1 : 0,
                    'status' => 1,
                    'isdelete' => 0,
                    'end_time' => strtotime(date('Y-m-d 23:59:59', strtotime('+1 day')) . " +3  year"),
                ];
                $storeId = Db::name('store')->insertGetId($saveArray);
                
                //添加卖家账号seller
                $saveArray = [
                    'seller_name' => $_POST['seller_name'],
                    'member_id' => $memberId,
                    'store_id' => $storeId,
                    'seller_group_id' => 0,
                    'is_admin' => 1,
                ];
                $sellerId = Db::name('seller')->insertGetId($saveArray);
                if ($type === 'own') {
                    //自营店铺绑定所有分类
                    $store_bind_class_array = [];
                    $store_bind_class = \Fields::getById('goods_class');
                    foreach ($store_bind_class as $key => $val) {
                        if (!empty($val['_child']) && is_array($val['_child'])) {
                            foreach ($val['_child'] as $key1 => $val1) {
                                $store_bind_class_array[] = [
                                    'store_id' => $storeId,
                                    'commis_rate' => $val1['commis_rate'],
                                    'class_1' => $val1['pid'],
                                    'class_2' => $val1['id'],
                                    'state' => 1
                                ];
                            }
                        }
                    }
                    $result = Db::name('store_bind_class')->insertAll($store_bind_class_array);
                } else{
                    //添加入驻信息joinin，自营店铺不用加
//                    $saveArray = [
//                        'company_name' => $data['store_name'],
//                        'seller_name' => $data['seller_name'],
//                        'store_name' => $data['store_name'],
//                        'company_area_code' => 0,
//                        'member_name' => $data['member_name'],
//                        'member_id' => $memberId,
//                        'joinin_state' => 40,
//                        'company_area_code' => 0,
//                        'sc_bail' => 0,
//                        'joinin_year' => 3,
//                    ];
//                    $joininId = Db::name('store_joinin')->insertGetId($saveArray);
                }
                // 添加相册默认
                $saveArray = [
                    'aclass_name' => '默认相册',
                    'store_id' => $storeId,
                    'aclass_des' => '',
                    'aclass_sort' => '255',
                    'aclass_cover' => '',
                    'upload_time' => time(),
                    'is_default' => '1',
                ];
                Db::name('album_class')->insertGetId($saveArray);
                Db::commit();
                return ajax_return_adv('操作成功');
            } catch (Exception $e) {
                Db::rollback();
                throw new Exception($e->getMessage());
            }
        }else{
            return $this->view->fetch();
        } 
    }
    
    public function edit(){
        $store_id = $this->request->param('id/d',0);
        if($this->request->isPost()){
            $type = $this->request->param('type/s', 'store');
            try {
                if ($type == 'store') {
                    //保存店铺信息
                    $data = [
                        'name' => $this->request->param('name/s', ''),
                        'company_name' => $this->request->param('company_name/s', ''),
                        'areacode' => $this->request->param('areacode/d', ''),
                        'area_info' => $this->request->param('area_info/s', ''),
                        'sc_id' => $this->request->param('store_class/d', 0),
                        'grade_id' => $this->request->param('store_grade/d', 0),
                        'store_state' => $this->request->param('store_state/d', ''),
                        'end_time' => strtotime($this->request->param('end_time/s', '') . ' 00:00:00'),
                    ];
                    $result = Db::name('store')->where(['id' => $store_id])->update($data);
                    return ajax_return_adv('保存成功', '');
                } elseif ($type == 'joinin') {
                    //保存注册信息
                    $member_id = $this->request->param('member_id/d', 0);
                    $joinin_info = Db::name('store_joinin')->where(['member_id' => $member_id])->find();
                    if (empty($joinin_info)) {
                        return ajax_return_adv_error('没有该注册信息');
                    }
                    $data = $this->request->except('member_id,type');
                    $validate = validate('store_joinin');
                    if (!$validate->check($data)) {
                        return ajax_return_adv_error($validate->getError());
                    }
                    $result = Db::name('store_joinin')->where(['member_id' => $member_id])->update($data);
                    return ajax_return_adv('保存成功', '');
                }
            } catch (Exception $e) {
                throw new Exception($e->getMessage());
            }
        }else{
            //入驻信息
            $store_info = Db::name('store')->where(['id'=>$store_id])->find();
            $store_joinin = Db::name('store_joinin')->where(['member_id'=>$store_info['member_id']])->find();
            if(!empty($store_joinin)){
                $store_joinin['store_class_names'] = unserialize($store_joinin['store_class_names']);
                $class_name = [];
                if(!empty($store_joinin['store_class_names'])){
                    foreach ($store_joinin['store_class_names'] as $key => $val) {
                        $tmp = explode(',', $val);
                        $class_name[] = [
                            'class_1_name' => $tmp[0],
                            'class_2_name' => $tmp[1]
                        ];
                    }
                }
                $store_joinin['store_class_names'] = $class_name;
                $store_joinin['store_class_commis_rates'] = explode(',', $store_joinin['store_class_commis_rates']);
            }
            //店铺等级
            $store_grade = \Fields::getById('store_grade');
            //店铺分类
            $store_class = \Fields::getById('store_class');
            $this->view->assign('joinin_info',$store_joinin);
            $this->view->assign('store_grade',$store_grade);
            $this->view->assign('store_class',$store_class);
            $this->view->assign('vo',$store_info);
            return $this->view->fetch();
        } 
    }
    
    /**
     * 经营类目编辑页
     */
    public function store_bind_class_edit()
    {
        // 店铺信息
        $store_id = $this->request->get('store_id/d');
        
        $store_info = Db::name('store')->where([
            'id' => $store_id
        ])->find();
        if (empty($store_info)) {
            showMessage('没有商家信息', '', '', 'error');
        }
        $this->view->assign('store_info', $store_info);
        
        $store_bind_class_list = Db::name('store_bind_class')->where([
            'store_id' => $store_id,
            'state' => [
                'in',
                '1,2'
            ],
            'status' => 1,
            'isdelete' => 0
        ])->select();
        $goods_class = \Fields::getById("goods_class"); 
        $this->view->assign('goods_class', $goods_class);
        for ($i = 0, $j = count($store_bind_class_list); $i < $j; $i ++) {
            $store_bind_class_list[$i]['class_1_name'] = $goods_class[$store_bind_class_list[$i]['class_1']]['name'];
            $store_bind_class_list[$i]['class_2_name'] = $goods_class[$store_bind_class_list[$i]['class_1']]['_child'][$store_bind_class_list[$i]['class_2']]['name'];
            // $store_bind_class_list[$i]['class_3_name'] = $goods_class[$store_bind_class_list[$i]['class_3']]['name'];
        }
        $this->view->assign('store_bind_class_list', $store_bind_class_list);
        // 获取商铺所有规格列表
        $spec_list = [];
        $spec = \Fields::getById('goods_spec'); // 系统所有规格信息
        foreach ($store_bind_class_list as $key => $val) {
            if (isset($goods_class[$val['class_1']]['type_id']) && ! empty($goods_class[$val['class_1']]['type_id'])) {
                $type_spec = Db::name('goods_type_spec')->where([
                    'type_id' => $goods_class[$val['class_1']]['type_id']
                ])->select();
                $spec_info = [];
                if (! empty($type_spec)) {
                    foreach ($type_spec as $key1 => $val1) {
                        foreach ($spec as $key2 => $val2) {
                            if ($val2['sp_id'] == $val1['spec_id']) {
                                $spec_info[] = [
                                    'id' => $val2['sp_id'],
                                    'name' => $val2['name']
                                ];
                            }
                        }
                    }
                }
                $spec_list[$val['class_2']] = $spec_info;
            }
        }
        $this->view->assign('spec_list', $spec_list);
        $this->view->assign('store_id', $store_id);
        return $this->view->fetch();
    }
    
    /**
     * 添加经营类目
     */
    public function store_bind_class_add()
    {
        $store_id = $this->request->param('store_id/d');
        $commis_rate = $this->request->param('commis_rate/d');
        if($commis_rate < 0 || $commis_rate > 100) {
            return ajax_return_adv_error('请填写正确的分佣比例'); 
        }
        list($class_1, $class_2, $class_3) = explode(',', $this->request->param('goods_class'));
        $param = array();
        $param['store_id'] = $store_id;
        $param['class_1'] = $class_1;
        $param['state'] = 1;
        if(!empty($class_2)) {
            $param['class_2'] = $class_2;
        }
        if(!empty($class_3)) {
            $param['class_3'] = $class_3;
        }
        // 检查类目是否已经存在
        $store_bind_class_info = Db::name('store_bind_class')->where($param)->find();
        if(!empty($store_bind_class_info)) {
            return ajax_return_adv_error('该类目已经存在');
        }
        $param['commis_rate'] = $commis_rate;
        $result = Db::name('store_bind_class')->insertGetId($param);

        if($result) {
            //添加默认类型
            $spec['sp_id'] = 2;
            $spec['gc_id'] = $param['class_2'];
            $spec['store_id'] = $store_id;
            $spec['sp_value_name'] = '默认服务';
            Db::name('spec_value')->insertGetId($spec);
		
            //$this->log('删除店铺经营类目，类目编号:'.$result.',店铺编号:'.$store_id);
            return ajax_return_adv('添加成功','');
        } else {
            return ajax_return_adv_error('添加失败');
        }
    }

    /**
     * 经营类目对应规格编辑页
     */
    public function store_bind_class_spec_edit()
    {
        $store_id = $this->request->param('store_id/d');
        $class_id = $this->request->param('class_id/d');
        $sp_id = $this->request->param('sp_id/d');
        if ($this->request->isPost()) {
            $node = $this->request->param('node/a');
            // 更新数据
            Db::startTrans();
            try {
                $data = [];
                //先删除相关属性
                Db::name('spec_value')->where([
                    'sp_id' => $sp_id,
                    'gc_id' => $class_id,
                    'store_id' => $store_id
                ])->delete();
                if(!empty($node) && is_array($node)){
                    foreach ($node as $key => $value) {
                        $data[] = [
                            'store_id' => $store_id,
                            'gc_id' => $class_id,
                            'sp_id' => $sp_id,
                            'sp_value_name' => $value['spec_name']
                        ];
                    }
                    Db::name('spec_value')->insertAll($data);
                }
                Db::commit();
                // 提交事务
                return ajax_return_adv('保存成功');
            } catch (Exception $e) {
                // 回滚事务
                Db::rollback();
                return ajax_return_adv_error($e->getMessage());
            }
        } else {
            // 展示页面
            $spec_info = Db::name('spec_value')->where([
                'store_id' => $store_id,
                'gc_id' => $class_id,
                'sp_id' => $sp_id
            ])->select();
            $check_name = array_keys(reset_by_key($spec_info, 'sp_value_name')); // 已选属性名字列表
            $this->view->assign('check_name', json_encode($check_name));
            if ($sp_id == self::$_spec_area) {
                return $this->view->fetch('store_area');
            } elseif ($sp_id == self::$_spec_city) {
                return $this->view->fetch('store_city');
            }             /*
             * elseif ($sp_id == self::$_spec_type) { return "此规格不能编辑"; }
             */
            else {
                $spec_index_info = Db::name('spec_index')->where([
                    'sp_id' => $sp_id
                ])->select();
                $this->view->assign('check_name', $check_name);
                $this->view->assign('spec_index_info', $spec_index_info);
                return $this->view->fetch('store_spec');
            }
        }
    }

    /**
     * 添加规格值
     */
    public function spec_index_save()
    {
        $name = $this->request->param('name/s');
        $sp_id = $this->request->param('sp_id/d');
        if ($name == '' || $sp_id <= 0) {
            echo json_encode(array(
                'done' => false
            ));
            die();
        }
        $insert = array(
            'sp_index_name' => $name,
            'sp_id' => $sp_id,
            'create_time' => time()
        );
        $index_id = Db::name('spec_index')->insertGetId($insert);
        if ($index_id) {
            echo json_encode(array(
                'done' => true,
                'index_id' => $index_id
            ));
            die();
        } else {
            echo json_encode(array(
                'done' => false
            ));
            die();
        }
    }

    /**
     * 删除规格值
     */
    public function spec_index_del()
    {
        $index_id = $this->request->param('spec_index_id/d');
        if ($index_id <= 0) {
            echo json_encode(array(
                'done' => false
            ));
            die();
        }
        $spec_index = Db::name('spec_index')->where([
            'sp_index_id' => $index_id
        ])->find();
        if (empty($spec_index)) {
            echo json_encode(array(
                'done' => false,
                'msg' => '无' . $spec_index['sp_index_name'] . '规格信息'
            ));
            die();
        }
        $store_binding = Db::name('spec_value')->where([
            'sp_id' => $spec_index['sp_id'],
            'sp_value_name' => $spec_index['sp_index_name']
        ])->find();
        if (! empty($store_binding)) {
            // 如有商家绑定规格选项，则不能删除，直接退出
            echo json_encode(array(
                'done' => false,
                'msg' => '有商家授权' . $store_binding["sp_value_name"] . '规格,无法删除'
            ));
            die();
            exit();
        }
        $result = Db::name('spec_index')->where([
            'sp_index_id' => $index_id
        ])->delete();
        if ($result) {
            echo json_encode(array(
                'done' => true
            ));
            die();
        } else {
            echo json_encode(array(
                'done' => false
            ));
            die();
        }
    }
}